#!/bin/bash

# MessageFramework性能测试运行脚本

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}MessageFramework性能测试套件${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 检查构建目录
if [ ! -d "../build" ]; then
    echo -e "${RED}错误: 未找到build目录${NC}"
    echo "请先运行: cd .. && mkdir build && cd build && cmake .. && make"
    exit 1
fi

cd ../build

# 检查Redis连接
echo -e "${YELLOW}检查Redis连接...${NC}"
if ! redis-cli -a "redis_EX7Nms" ping > /dev/null 2>&1; then
    echo -e "${RED}错误: 无法连接到Redis${NC}"
    echo "请确保Redis服务正在运行：redis-server"
    exit 1
fi
echo -e "${GREEN}✓ Redis连接正常${NC}"
echo ""

# 清理Redis测试数据
echo -e "${YELLOW}清理Redis测试数据...${NC}"
redis-cli -a "redis_EX7Nms" --scan --pattern "test_*" | xargs -r redis-cli -a "redis_EX7Nms" DEL > /dev/null 2>&1 || true
echo -e "${GREEN}✓ Redis清理完成${NC}"
echo ""

# 性能测试列表
PERFORMANCE_TESTS=(
    "test_throughput"
    "test_latency"
    "test_concurrency"
)

# 运行性能测试
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}运行性能测试...${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

TOTAL_PASSED=0
TOTAL_FAILED=0

for test in "${PERFORMANCE_TESTS[@]}"; do
    if [ ! -f "./$test" ]; then
        echo -e "${YELLOW}跳过: $test (未找到可执行文件)${NC}"
        continue
    fi

    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}运行: $test${NC}"
    echo -e "${BLUE}========================================${NC}"

    # 清理Redis数据
    redis-cli -a "redis_EX7Nms" --scan --pattern "test_*" | xargs -r redis-cli -a "redis_EX7Nms" DEL > /dev/null 2>&1 || true

    if ./$test; then
        echo -e "${GREEN}✓ $test 通过${NC}"
        ((TOTAL_PASSED++))
    else
        echo -e "${RED}✗ $test 失败${NC}"
        ((TOTAL_FAILED++))
    fi
    echo ""
done

# 总结
TOTAL_TESTS=$((TOTAL_PASSED + TOTAL_FAILED))

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}性能测试总结${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "总测试数: $TOTAL_TESTS"
echo -e "${GREEN}通过: $TOTAL_PASSED${NC}"
echo -e "${RED}失败: $TOTAL_FAILED${NC}"
echo ""

if [ $TOTAL_FAILED -eq 0 ] && [ $TOTAL_TESTS -gt 0 ]; then
    echo -e "${GREEN}✓ 所有性能测试通过！${NC}"
    exit 0
elif [ $TOTAL_TESTS -eq 0 ]; then
    echo -e "${YELLOW}⚠ 未找到任何性能测试可执行文件${NC}"
    echo "请先编译: cd build && make"
    exit 1
else
    echo -e "${RED}✗ 有 $TOTAL_FAILED 个性能测试失败${NC}"
    exit 1
fi
